package gormx

import (
	"fmt"
	"reflect"
	"time"

	"gorm.io/gorm"
)

// from/to 非值类型
func WhereDateRange(field string, from, to interface{}) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if !reflect.ValueOf(from).IsNil() {
			switch v := from.(type) {
			case *time.Time:
				db = db.Where(fmt.Sprintf("%s >= ?", field), from)
			case *int64:
				db = db.Where(fmt.Sprintf("%s >= ?", field), time.Unix(*v, 0))
			}
		}

		if !reflect.ValueOf(to).IsNil() {
			switch v := from.(type) {
			case *time.Time:
				db = db.Where(fmt.Sprintf("%s < ?", field), v.AddDate(0, 0, 1))
			case *int64:
				db = db.Where(fmt.Sprintf("%s < ?", field), time.Unix(*v, 0).AddDate(0, 0, 1))
			}
		}

		return db
	}
}
